<template>
    <div>
        <h2 style="text-align: left;padding-left: 15px;">验证码登录</h2>
        <van-form @submit="handleLogin">
            <span class="field_title">手机号码</span>
            <van-field
                    v-model="username"
                    label=""
                    placeholder="输入手机号"
                    clearable
                    :rules="[{ required: true, message: '' },{ validator: validatorUsername, message: '格式有错误' }]"
            >
                <!-- 通过 button 插槽可以在输入框尾部插入按钮 -->
                <template #button>
                    <span @click="getCode" v-show="sendAuthCode">发送验证码</span>
                    <span v-show="!sendAuthCode" class="auth_text">
                  <span class="auth_text_blue">{{ auth_time }} </span>
                  秒之后重新发送
          </span>
                </template>
            </van-field>
            <span class="field_title">验证码</span>
            <van-field
                    ref="input"
                    label=""
                    placeholder="输入验证码"
                    v-model="code"
                    clearable
                    :rules="[{ required: true, message: ''}]"
            />
            <van-field name="checkboxGroup" :rules="[{ required: true, message: '请同意' }]">
                <template #input>
                    <van-checkbox name="1" shape="square" v-model="checked">我已阅读并同意《用户协议》和《隐私政策》</van-checkbox>
                    <!-- <van-checkbox-group v-model="checkboxGroup" direction="horizontal">
                       <van-checkbox name="1" shape="square">我已阅读并同意《用户协议》和《隐私政策》</van-checkbox>
                     </van-checkbox-group>-->
                </template>
            </van-field>

            <div style="margin: 16px;text-align: center;">
                <van-button round block type="info" native-type="submit" v-if="!isLogin" class="btn" @click="submit()">登 录</van-button>
                <van-loading type="spinner" color="#1989fa" v-else/>
            </div>
        </van-form>
    </div>
</template>

<script>
    import {validPhone} from '@/utils/validate';
    import {getQlCode,login} from '@/api/login';
    import {shoppingLogin} from '@/api/login-shopping';
    import {Toast} from 'vant'
    export default {
        name: "loginIndex",
        data(){
            return {
                auth_time: 0 /*倒计时 计数器*/,
                sendAuthCode: true,
                isLogin: false,
                username: undefined,
                code: undefined,
                checked: false
            }
        },
        methods: {
            submit(){
                if(!this.username){
                    return this.dialogNotifyError("请输入手机号");
                }else if (! validPhone(this.username)){
                    return this.dialogNotifyError("请输入正确的手机号");
                }else if (!this.code){
                    return this.dialogNotifyError("请输入验证码");
                }else if (this.code.length != 6){
                    return this.dialogNotifyError("请输入正确的验证码");
                }else if (!this.checked){
                    return this.dialogNotifyError("请同意用户协议");
                }
                login(this.username,this.code).then(response=>{
                    // 清除缓存
                    this.removeToken();
                    sessionStorage.removeItem("loginToken")
                    console.log("登录成功",response);
                    localStorage.setItem("phone",this.username);
                    if (response.code == 0){
                        // 商城登录
                        /*shoppingLogin(this.username,response.data.token,'wx89e65f1ed64a91ee','1','ooKbW5-ZXKT-ztpaNexaNTigWGOw').then(response=>{
                            Toast(response.code)
                        });*/
                        // 存一个临时token
                        sessionStorage.setItem("loginToken",response.data.token);
                        const data = JSON.stringify(response.data);
                        if(response.data.infoState == 0){
                            //请录入信息 跳转到录入信息页面  name和params可以一起使用   【path不能与params一起使用 冲突   太坑了】
                            this.$router.push({name: "register",params:{data: data}});
                        }else{
                            //已存在录入信息.跳转到首页面
                            // 存token
                            this.setToken(response.data.token);
                            this.$router.push("/");
                        }
                    }
                }).finally((error)=>{
                    if(error) console.log(error);
                });
            },
            getCode(){
                this.$refs.input.focus()
                console.log('获得手机验证码......')
                this.code = undefined;
                if(!this.username)
                    return this.dialogNotifyError("请输入手机号，再进行发送验证码");
                if(! validPhone(this.username))
                    return this.dialogNotifyError("请输入正确的手机号");
                this.loading = true;
                getQlCode(this.username).then(response=>{
                    console.log("发送验证码--->",response);
                    Toast("验证码已发");
                }).finally(()=>{
                    this.loading = false;
                });
                //设置倒计时秒
                this.auth_time = 60;
                this.sendAuthCode = false
                let auth_timeTimer = setInterval(() => {
                    this.auth_time--;
                    if (this.auth_time <= 0) {
                        this.sendAuthCode = true;
                        clearInterval(auth_timeTimer);
                        this.isLogin = false;
                    }
                }, 1000);

            },
            validatorUsername(val) {
                return validPhone(val);
            },
            async handleLogin(){
                this.isLogin = false;
                this.$refs.input.blur(); //失去鼠标焦点
                // 验证表单
                console.log("登录验证")
                if(!this.checked)
                    return this.dialogNotifyError("请同意隐私协议");

            }
        },
        created(){
            // 显示头部信息
            this.$store.commit('showMenu');
            console.log("login...............");
            let recommendCode = this.getUrlArgusString("recommendCode");
            localStorage.setItem("recommendCode",recommendCode);
            console.log(localStorage.getItem("recommendCode") == "null");
        }
    }
</script>

<style scoped>
    .field_title{display:block;text-align: left;padding: 15px 15px 0px 15px;}
    .btn{background: #CCCCCC;border: none;border-radius: 0px;color: black;}
</style>
